package com.haixue.android.academy.view.tiku;

import android.academy.haixue.com.haixue.R;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class ImageGetterFromHTTP extends BaseImageGetter   {

	private TextView tv;

	private float scale;


	public ImageGetterFromHTTP(Context context, TextView tv) {
		super(context);
		scale = context.getResources().getDisplayMetrics().density;
		this.tv = tv;
	}

	@Override
	public Drawable getDrawable(String source) {
		// TODO Auto-generated method stub
		String imageName = Common.md5(source);
		String sdcardPath = Environment.getExternalStorageDirectory().toString();

		String[] ss = source.split("\\.");
		String ext = ss[ss.length - 1];

		String savePath = sdcardPath + "/" + context.getPackageName() + "/" + imageName + "." + ext;

		File file = new File(savePath);

		if (file.exists()) {
			Drawable drawable = Drawable.createFromPath(savePath);
			int imageDisplayWidth = 0;
			//			if (maxWidth > -1 && drawable.getIntrinsicWidth() > maxWidth) {
			//				imageDisplayWidth = maxWidth;
			//			} else {
			//				imageDisplayWidth = drawable.getIntrinsicWidth();
			//			}
			if (maxWidth > -1 && (drawable.getIntrinsicWidth() * scale) > maxWidth) {
				imageDisplayWidth = maxWidth;
			} else {
				imageDisplayWidth = (int) (drawable.getIntrinsicWidth() * scale);
			}
			return DrawableZoomer.zoomDrawableByWidth(drawable, imageDisplayWidth);
		}

		Resources res = context.getResources();
		URLDrawable drawable = new URLDrawable(res.getDrawable(R.drawable.defualt_image));
		new ImageAsync(drawable).execute(savePath, source);
		return drawable;

	}

	private class ImageAsync extends AsyncTask<String, Integer, Drawable> {

		private URLDrawable drawable;

		public ImageAsync(URLDrawable drawable) {
			this.drawable = drawable;
		}

		@SuppressWarnings("resource")
		@Override
		protected Drawable doInBackground(String... params) {
			// TODO Auto-generated method stub
			String savePath = params[0];
			String url = params[1];

			InputStream in = null;
			try {

				if (url.contains("http")) {
					HttpGet http = new HttpGet(url);
					HttpClient client = new DefaultHttpClient();					
					HttpResponse response = (HttpResponse) client.execute(http);					
					BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(response.getEntity());
					in = bufferedHttpEntity.getContent();					
				} else {

					in = context.getResources().getAssets().open(url);

				}

			} catch (Exception e) {
				
			
				try {
					if (in != null)
						in.close();
					
					//return drawable;
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
            
			if (in == null)
				return null;

			try {
				File file = new File(savePath);
				String basePath = file.getParent();
				File basePathFile = new File(basePath);

				if (!basePathFile.exists()) {
					basePathFile.mkdirs();
				}

				file.createNewFile();
				FileOutputStream fileout = new FileOutputStream(file);
				byte[] buffer = new byte[4 * 1024];
				while (in.read(buffer) != -1) {
					fileout.write(buffer);
				}
				fileout.flush();

				Drawable mDrawable = Drawable.createFromPath(savePath);

				int imageDisplayWidth = 0;
				if (maxWidth > -1 && (mDrawable.getIntrinsicWidth() * scale) > maxWidth) {
					imageDisplayWidth = maxWidth;
				} else {
					imageDisplayWidth = (int) (mDrawable.getIntrinsicWidth() * scale);
				}

				//				return DrawableZoomer.zoomDrawableByHeight(mDrawable, 200);
				return DrawableZoomer.zoomDrawableByHeight(mDrawable, imageDisplayWidth);
			} catch (Exception e) {
				// TODO: handle exception
			}
			return DrawableZoomer.zoomDrawableByWidth(drawable, 200);
		}

		@Override
		protected void onPostExecute(Drawable result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result != null) {
				drawable.setDrawable(result);
				tv.setText(tv.getText());
				//消除引用
				//result.setCallback(null);
				result=null;
			}
		}

	}

	public class URLDrawable extends BitmapDrawable {

		private Drawable drawable;

		@SuppressWarnings("deprecation")
		public URLDrawable(Drawable defaultDraw) {
			setDrawable(defaultDraw);
		}

		private void setDrawable(Drawable nDrawable) {
			drawable = nDrawable;
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
			setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
		}

		@Override
		public void draw(Canvas canvas) {
			// TODO Auto-generated method stub
			drawable.draw(canvas);
		} 
		

	}
}
